/*
 * jPOS Project [http://jpos.org]
 * Copyright (C) 2000-2017 jPOS Software SRL
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.jpos.util;

import org.jpos.core.Configurable;
import org.jpos.core.Configuration;
import org.jpos.core.ConfigurationException;
import org.jpos.q2.Q2;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * Peer class Logger forwards LogEvents generated by LogSources 
 * to LogListeners.
 * <br>
 * This little <a href="/doc/LoggerGuide.html">tutorial</a>
 * give you additional information on how to extend the jPOS's
 * Logger subsystem.
 *
 * @author apr@cs.com.uy
 * @version $Id$
 * @see LogEvent
 * @see LogSource
 * @see LogListener
 * @see Loggeable
 * @see SimpleLogListener
 * @see RotateLogListener
 */
@SuppressWarnings("unchecked")
public class Logger implements LogProducer,Configurable
{
    Configuration cfg;
    String name;
    List<LogListener> listeners;
    public static final String NRPREFIX = "logger.";

    public Logger () {
        super();
        listeners = Collections.synchronizedList(new ArrayList<>());
        name = "";
    }

    public Configuration getConfiguration()
    {
        return cfg;
    }

    @Override
    public void setConfiguration(Configuration cfg) throws ConfigurationException
    {
        this.cfg = cfg;
    }

    public void addListener (LogListener l) {
        listeners.add(l);
    }
    public void removeListener (LogListener l) {
        listeners.remove(l);
    }
    public void removeAllListeners () {
        for (Object l : listeners) {
            if (l instanceof Destroyable) {
                ((Destroyable) l).destroy();
            }
        }
        listeners.clear ();
    }
    public static void log (LogEvent evt) {
        Logger l = null;
        LogSource source = evt.getSource();
        if (source != null)
            l = source.getLogger();
        if (l == null && !evt.isHonorSourceLogger()) {
            l = getLogger(Q2.LOGGER_NAME);
        }
        if (l != null && l.hasListeners ()) {
            Iterator i = l.listeners.iterator();
            while (i.hasNext() && evt != null) {
                try {
                    evt = ((LogListener) i.next()).log(evt);
                } catch (Throwable t) {
                    evt.addMessage (t);
                }
            }
        }
    }
    /**
     * associates this Logger with a name using NameRegistrar
     * @param name name to register
     * @see NameRegistrar
     */
    public void setName (String name) {
        this.name = name;
        NameRegistrar.register (NRPREFIX+name, this);
    }
    /**
     * destroy logger
     */
    public void destroy () {
        NameRegistrar.unregister (NRPREFIX+name);
        removeAllListeners ();
    }
    /**
     * @return logger instance with given name. Creates one if necessary
     * @see NameRegistrar
     */
    public synchronized static Logger getLogger (String name) {
        Logger l;
        try {
            l = (Logger) NameRegistrar.get (NRPREFIX+name);
        } catch (NameRegistrar.NotFoundException e) {
            l = new Logger();
            l.setName (name);
        }
        return l;
    }
    /**
     * @return this logger's name ("" if no name was set)
     */
    public String getName() {
        return this.name;
    }
    /**
     * Used by heavy used methods to avoid LogEvent creation 
     * @return true if Logger has associated LogListsners
     */
    public boolean hasListeners() {
        return !listeners.isEmpty();
    }
}
